
package CCosmoCompressor;
import java.io.*;
import FileBitIO.*;

//Fixed Length Encoder

public class CCosmoDecoder implements cosmoInterface{
	
	private String fileName,outputFilename;
	private char[] encodedChars = new char[MAXCHARS];
	private int distinctChars = 0;
	private long fileLen=0,outputFilelen;
	private FileOutputStream outf;
	private String gSummary;

	
	void resetCodes(){
		for(int i=0;i<MAXCHARS;i++)
		encodedChars[i] = 0;
		
		
		distinctChars = 0;
		fileLen=0;
		gSummary ="";
		}
	
	public CCosmoDecoder  (){
		loadFile("","");
		}
	public CCosmoDecoder  (String txt){
		loadFile(txt);
		}
	public CCosmoDecoder  (String txt,String txt2){
		loadFile(txt,txt2);
		}
		
	public void loadFile(String txt){
		fileName = txt;
		outputFilename = stripExtension(txt,strExtension);
		resetCodes();
		}
	public void loadFile(String txt,String txt2){
		fileName = txt;
		outputFilename = txt2;
		resetCodes();
		}
		
	String stripExtension(String ff,String ext){
		ff = ff.toLowerCase();
		if(ff.endsWith(ext.toLowerCase())){
			return ff.substring(0,ff.length()-ext.length());
			}
		return "_" + ff;
		}

	public boolean decodeFile() throws Exception{
		
		
		if(fileName.length() == 0) return false;
		
		CFileBitReader fin = new CFileBitReader(fileName);
		fileLen = fin.available();

		String buf;
		buf = fin.getBytes(cosSignature.length());
		
		if(!buf.equals(cosSignature)) return false;
		outputFilelen = Long.parseLong(fin.getBits(32),2);
		distinctChars = Integer.parseInt(fin.getBits(8),2);
		gSummary  += ("Compressed File Size : "+ fileLen + "\n");
		gSummary  += ("Original   File Size : "+ outputFilelen + "\n");
		gSummary  += ("Distinct   Chars     : "+ distinctChars + "\n");
		
				
		if(distinctChars > 128 || distinctChars == 0) throw new Exception("Fatal Error : Possibly Corrupt File!");
		
		int nMaxbits=2,nBits=1;
		while(nMaxbits <= distinctChars){
			nMaxbits *= 2;
			nBits++;
		}

		if(nBits >= 8) return false;

		
		for(int i=0;i<distinctChars;i++){
			encodedChars[i] = (char)Integer.parseInt(fin.getBits(8),2);
			//System.out.println((char)ch + " : "  + hCodes[ch]);
			}
		
		try{
		
		outf = new FileOutputStream(outputFilename);
		int i = 0;
		
		int ch;
		
		while(i < outputFilelen){	
			ch = Integer.parseInt(fin.getBits(nBits),2);
			outf.write(encodedChars[ch]);
			i++;
			}
		
		outf.close();
		return true;
		
		}catch(Exception e){
			throw e;
		}
		

		}


	String leftPadder(String txt,int n){
		while(txt.length() < n )
			txt =  "0" + txt;
		return txt;
		}
	
	String rightPadder(String txt,int n){
		while(txt.length() < n )
			txt += "0";
		return txt;
		}
		
	public String getSummary(){
		return gSummary;
		}

	
	}


